package com.study.cloud.utils;

import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author: keeley
 * DateTime: 2021-01-18 4:39 下午
 */
public class TraceIdUtil {
    public static final String TRACE_ID = "traceId";

    /**
     * 设置traceId
     */
    public static String initTraceId() {
        //将traceId放到MDC中
        String str = genTraceId();
        MDC.put(TRACE_ID, str);
        return str;
    }

    /**
     * 设置traceId
     */
    public static void setTraceId(String traceId) {
        //如果参数为空，则设置默认traceId
        traceId = StringUtils.isEmpty(traceId) ? genTraceId() : traceId;
        //将traceId放到MDC中
        MDC.put(TRACE_ID, traceId);
    }

    /**
     * 获取traceId
     */
    public static String getTraceId() {
        return MDC.get(TRACE_ID);
    }

    public static void clear(){
        MDC.remove(TRACE_ID);
    }
    /**
     * 生成traceId
     */
    private static String genTraceId() {
        return UUID.randomUUID().toString().replace("-", "").toLowerCase();
    }
}